<template>
  <div class="dashboard-container">
    <div class="dashboard-header">
      <h1>欢迎使用纪念品商城管理系统</h1>
    </div>
    
    <!-- 数据概览卡片 -->
    <el-row :gutter="20">
      <el-col :span="6" v-for="(item, index) in statisticsData" :key="index">
        <el-card class="statistics-card" shadow="hover" v-loading="statsLoading">
          <div class="card-content">
            <el-icon class="card-icon" :style="{ color: item.color }">
              <component :is="item.icon" />
            </el-icon>
            <div class="card-info">
              <div class="card-value">{{ item.value }}</div>
              <div class="card-title">{{ item.title }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>商品销售趋势</span>
              <el-button 
                type="primary" 
                size="small" 
                @click="refreshSalesTrend"
                :loading="salesTrendLoading"
              >
                刷新
              </el-button>
            </div>
          </template>
          <div ref="salesChart" class="chart-container" v-loading="salesTrendLoading"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>商品分类占比</span>
              <el-button 
                type="primary" 
                size="small" 
                @click="refreshCategoryStats"
                :loading="categoryStatsLoading"
              >
                刷新
              </el-button>
            </div>
          </template>
          <div ref="categoryChart" class="chart-container" v-loading="categoryStatsLoading"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { getDashboardStats, getSalesTrend, getCategoryStats } from '@/api/dashboard'

const router = useRouter()

// 加载状态
const statsLoading = ref(false)
const salesTrendLoading = ref(false)
const categoryStatsLoading = ref(false)

// 统计数据
const statisticsData = reactive([
  { title: '总订单数', value: 0, icon: 'Tickets', color: '#409EFF' },
  { title: '总用户数', value: 0, icon: 'User', color: '#67C23A' },
  { title: '商品数量', value: 0, icon: 'ShoppingBag', color: '#E6A23C' },
  { title: '总收入', value: '¥0', icon: 'Money', color: '#F56C6C' }
])

// 图表引用
const salesChart = ref(null)
const categoryChart = ref(null)

// 图表实例
let salesChartInstance = null
let categoryChartInstance = null

// 格式化金额
const formatCurrency = (amount) => {
  return `¥${amount.toLocaleString()}`
}

// 获取统计数据
const fetchStats = async () => {
  statsLoading.value = true
  try {
    const res = await getDashboardStats()
    if (res.code === 200) {
      const data = res.data
      statisticsData[0].value = data.totalOrders.toLocaleString()
      statisticsData[1].value = data.totalUsers.toLocaleString()
      statisticsData[2].value = data.totalGoods.toLocaleString()
      statisticsData[3].value = formatCurrency(data.totalRevenue)
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败')
  } finally {
    statsLoading.value = false
  }
}

// 获取销售趋势数据
const fetchSalesTrend = async () => {
  salesTrendLoading.value = true
  try {
    const res = await getSalesTrend()
    if (res.code === 200) {
      const data = res.data
      updateSalesChart(data)
    }
  } catch (error) {
    console.error('获取销售趋势数据失败:', error)
    ElMessage.error('获取销售趋势数据失败')
  } finally {
    salesTrendLoading.value = false
  }
}

// 获取分类统计数据
const fetchCategoryStats = async () => {
  categoryStatsLoading.value = true
  try {
    const res = await getCategoryStats()
    if (res.code === 200) {
      const data = res.data
      updateCategoryChart(data)
    }
  } catch (error) {
    console.error('获取分类统计数据失败:', error)
    ElMessage.error('获取分类统计数据失败')
  } finally {
    categoryStatsLoading.value = false
  }
}

// 更新销售趋势图表
const updateSalesChart = (data) => {
  if (!salesChartInstance) return
  
  salesChartInstance.setOption({
    title: {
      text: ''
    },
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        let result = params[0].name + '<br/>'
        params.forEach(param => {
          if (param.seriesName === '销售额') {
            result += `${param.marker}${param.seriesName}: ¥${param.value.toLocaleString()}<br/>`
          } else {
            result += `${param.marker}${param.seriesName}: ${param.value}单<br/>`
          }
        })
        return result
      }
    },
    legend: {
      data: ['销售额', '订单数']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: data.dateLabels
    },
    yAxis: [
      {
        type: 'value',
        name: '销售额(元)',
        position: 'left',
        axisLabel: {
          formatter: '¥{value}'
        }
      },
      {
        type: 'value',
        name: '订单数',
        position: 'right',
        axisLabel: {
          formatter: '{value}单'
        }
      }
    ],
    series: [
      {
        name: '销售额',
        type: 'line',
        yAxisIndex: 0,
        data: data.salesData,
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#409EFF'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(64, 158, 255, 0.7)'
            },
            {
              offset: 1,
              color: 'rgba(64, 158, 255, 0.1)'
            }
          ])
        }
      },
      {
        name: '订单数',
        type: 'line',
        yAxisIndex: 1,
        data: data.orderData,
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#67C23A'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(103, 194, 58, 0.7)'
            },
            {
              offset: 1,
              color: 'rgba(103, 194, 58, 0.1)'
            }
          ])
        }
      }
    ]
  })
}

// 更新分类统计图表
const updateCategoryChart = (data) => {
  if (!categoryChartInstance) return
  
  // 构建图表数据
  const chartData = data.categoryNames.map((name, index) => ({
    name: name,
    value: data.categoryValues[index],
    itemStyle: {
      color: data.categoryColors[index]
    }
  }))
  
  categoryChartInstance.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}件 ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 10,
      data: data.categoryNames
    },
    series: [
      {
        name: '商品分类',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold',
            formatter: '{b}\n{c}件'
          }
        },
        labelLine: {
          show: false
        },
        data: chartData
      }
    ]
  })
}

// 初始化图表
const initCharts = () => {
  // 初始化销售趋势图表
  salesChartInstance = echarts.init(salesChart.value)
  
  // 初始化商品分类占比图表
  categoryChartInstance = echarts.init(categoryChart.value)
  
  // 窗口大小改变时重新调整图表大小
  window.addEventListener('resize', () => {
    salesChartInstance?.resize()
    categoryChartInstance?.resize()
  })
}

// 刷新销售趋势
const refreshSalesTrend = () => {
  fetchSalesTrend()
}

// 刷新分类统计
const refreshCategoryStats = () => {
  fetchCategoryStats()
}

// 初始化所有数据
const initData = async () => {
  // 检查登录状态
  const token = localStorage.getItem('token') || sessionStorage.getItem('token')
  if (!token) {
    ElMessage.error('请先登录')
    setTimeout(() => {
      router.replace('/login')
    }, 1000)
    return
  }
  
  try {
    await Promise.all([
      fetchStats(),
      fetchSalesTrend(),
      fetchCategoryStats()
    ])
  } catch (error) {
    console.error('初始化数据失败:', error)
  }
}

onMounted(async () => {
  // 初始化图表
  initCharts()
  
  // 加载数据
  await initData()
})
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.dashboard-header {
  margin-bottom: 24px;
}

.dashboard-header h1 {
  font-size: 24px;
  color: #303133;
  margin: 0;
}

.statistics-card {
  margin-bottom: 20px;
  height: 108px;
}

.card-content {
  display: flex;
  align-items: center;
}

.card-icon {
  font-size: 48px;
  margin-right: 16px;
}

.card-info {
  flex: 1;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.card-title {
  font-size: 14px;
  color: #909399;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-container {
  height: 300px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>